<template>
  <div
    @cancel="cancel"
    :width="1200"
    :height="1000">
    <div layout="inline">
      <a-row :gutter="24">
        <a-col :span="7" class="tree-container">
          <a-tree
            show-search
            :dropdown-style="{ maxHeight: 400, overflow: 'auto' }"
            placeholder="请选择隐患单位"
            :allow-clear="true"
            :tree-default-expand-all="false"
            :tree-data="unitTree"
            @select="onSelect"
            :selected-keys="[unitId]"
            :replaceFields="replaceFields"
            :expandedKeys="expandKeys"
            @expand="expand"
          />
        </a-col>
        <a-col :span="17">
          <a-form-item label="姓名或工号">
            <a-input v-model="inputKey" allow-clear placeholder="请输入姓名或工号" style="display: inline-block"/>
          </a-form-item>
          <a-card>
            <a-button type="primary" @click="selectByKey">查询</a-button>
            <a-button style="margin-left: 8px" @click="() => {this.inputKey = ''; this.unitId=''; this.unitName=''; this.queryParam={} }">重置</a-button>
            <a-button style="margin-left: 8px" type="primary" icon="plus" @click="$refs.addUserForm.add()">新增人员</a-button>
            <s-table
              ref="table"
              :columns="columns"
              :data="loadData"
              :alert="null"
              :rowSelection="rowSelection"
              :rowKey="(record) => record.userId">
            </s-table>
            <add-user-form ref="addUserForm" @ok="handleOk()"></add-user-form>
          </a-card>
        </a-col>
      </a-row>
    </div>
  </div>
</template>

<script>
  import {
    getUnitTree,
    getVioUserListWithName
  } from '@/api/modular/system/violationManage'
  import addUserForm from './addUserForm'
  import { STable, XCard, XDown } from '@/components'
  import { Modal, Table, Drawer, Checkbox } from 'ant-design-vue'
  import { mapGetters } from 'vuex'
  const Util = {}
  Util.getIds = function (data) {
    const arr = []
    data.length && data.forEach((item) => {
      if (item.children && item.children.length) {
        arr.push(item.id)
        // item.children.forEach((item) => {
        //   arr.push(item.id)
        // })
      }
    })
    return arr
  }
  export default {
    components: {
      XDown,
      XCard,
      STable,
      Modal,
      Table,
      Drawer,
      Checkbox,
      addUserForm
    },
    computed: {
      rowSelection() {
        return {
          type: 'radio', // 单选按钮定义
          selectedRowKeys: [this.selectedRowKeys],
          onChange: (selectedRowKeys, selectedRows) => {
            this.setSelectResult(selectedRowKeys, selectedRows)
          }
        }
      },
      ...mapGetters(['userInfo'])
    },
    data() {
      return {
        Util,
        expandKeys: [],
        queryId: {
          id: ''
        },
        secondOraName: {
          id: ''
        },
        unitName: '',
        // userId: 0,
        visible: false,
        peopleList: [],
        inputKey: '',
        unitId: '',
        selectedName: null,
        selectedRowKeys: [],
        selectedRows: [],
        columns: [
          {
            title: '姓名',
            dataIndex: 'userName'
          },
          {
            title: '电话号码',
            dataIndex: 'mobile'
          },
          {
            title: '工号',
            dataIndex: 'employeeNo'
          },
          {
            title: '性别',
            dataIndex: 'userSex'
          },
          {
            title: '单位',
            dataIndex: 'organizationName'
          }
        ],
        loadData: (parameter) => {
          // console.log('hhhh:', parameter)
          return getVioUserListWithName(Object.assign(parameter, this.queryParam)).then((res) => {
            this.selectedRowKeys = []
            // console.log(res.data)
            res.data.rows.forEach(row => {
              if (row.userSex === 1) {
                row.userSex = '男'
              } else if (row.userSex === 2) {
                row.userSex = '女'
              } else if (row.userSex === 3) {
                row.userSex = '未知'
              } else {
                row.userSex = '未知'
              }
            })
            res.data.rows.forEach(item => {
              // 在这里进行每个元素的操作
              if (item.userId === this.userId) {
                this.selectedRowKeys = item.userId
                return res.data
              }
            })
            return res.data
          })
        },
        pagination: {
          total: 0,
          defaultPageSize: 20,
          showTotal: total => `共 ${total} 条数据`,
          showSizeChanger: true,
          pageSizeOptions: ['5', '10', '15', '20']
          // onShowSizeChange: (current, pageSize) => this.pageSize = pageSize
        },
        queryParam: {},
        treeLoading: true,
        unitTree: [],
        replaceFields: {
          key: 'id'
        }
      }
    },
    created() {
      // this.$refs.table.refresh()
      // console.log('进入了created')
      this.secondOraName.id = this.userInfo.secondOrganizationName
      // 获取违章单位树
      getUnitTree(Object.assign(this.secondOraName)).then(res => {
        // console.log('进入了接口内部')
        this.treeLoading = false
        this.unitTree = res.data
        if (res.data.length === 0) {
            this.secondOraName.id = '机关总部'
            getUnitTree(Object.assign(this.secondOraName)).then(res => {
              this.unitTree = res.data
            })
          }
        this.expandKeys = Util.getIds(res.data)
        // console.log('expandKeys:', this.expandKeys)
        // console.log('tree:', res.data)
      })
    },
    props: {
      userId: {
        type: String,
        default: null
      }
    },
    watch: {
      userId: {
        handler() {
          this.$refs.table.refresh()
        }
      }
    },
    methods: {
      handleOk() {
        this.$refs.table.refresh()
      },
      expand(e, item) {
        // console.log('出发了expand')
        // console.log(e, item)
        this.expandKeys = e
      },
      onShowSizeChange(current, pageSize) {
        this.pageSize = pageSize
      },
      setSelectResult(selectedRowKeys, selectedRows) {
        this.selectedRows = selectedRows
        this.selectedRowKeys = selectedRowKeys
        // console.log('选中的', selectedRowKeys, selectedRows)
        // console.log('selectedRows=' + this.selectedRows)
        // console.log('selectedRows.userName=' + this.selectedRows[0].userName)
        this.$refs.table.refresh(true)
        // console.log('selectedRows.userName=' + this.selectedRows[0].userId)
        this.$emit('chooseUser', this.selectedRows[0].userName, this.selectedRows[0].userId, this.selectedRows[0].organizationName, this.selectedRows[0].employeeNo)
      },
      // 当选择 checkbox 被点击时
      onSelectChange(selectedRowKeys, selectedRows) {
        this.$emit('update:selectedUser', selectedRows[0].name)
        // 关闭弹出窗口
        this.$message.success('选择' + selectedRows[0].name)
        this.$emit('close')
      },
      cancel() {
        this.$emit('cancel')
      },
      onSelect(selectedKeys, e) {
        const selectedNode = e.selectedNodes[0]
        if (selectedKeys.length > 0) {
          // 将选中的树节点ID存入unitid中
          this.unitId = selectedKeys[0]
          this.unitName = selectedNode.data.props.title
        } else {
          this.unitId = null
          this.unitName = null
        }
        this.queryParam.OrganizationName = this.unitName
        this.queryParam.OrganizationId = this.unitId
        this.unitId = null
        this.unitName = null
        this.$refs.table.refresh()
      },
      selectByKey() {
        this.queryParam.Keyword = this.inputKey
        this.$refs.table.refresh()
      }

    }
  }
</script>

<style scoped>
.tree-container {
  height: 720px;
  overflow-y: auto;
}
</style>
